package cn.crc.webpay;

import com.alipay.v3.ApiClient;
import com.alipay.v3.ApiException;
import com.alipay.v3.Configuration;
import com.alipay.v3.api.AlipayTradeApi;
import com.alipay.v3.model.*;
import com.alipay.v3.util.model.AlipayConfig;
import com.alipay.v3.util.model.CustomizedParams;

import java.util.ArrayList;
import java.util.List;

public class AlipayTradeApiCreate {

    public static void main(String[] args) throws ApiException {
        ApiClient defaultClient = Configuration.getDefaultApiClient();
        // 初始化alipay参数（全局设置一次）
        defaultClient.setAlipayConfig(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayTradeApi api = new AlipayTradeApi();
        AlipayTradeCreateModel data = new AlipayTradeCreateModel();

        // 设置商户订单号
        data.setOutTradeNo("20150320010101001");

        // 设置订单总金额
        data.setTotalAmount("88.88");

        // 设置订单标题
        data.setSubject("Iphone6 16G");

        // 设置产品码
        data.setProductCode("JSAPI_PAY");

        // 设置卖家支付宝用户ID
        data.setSellerId("2088102146225135");

        // uid参数未来计划废弃，存量商户可继续使用，新商户请使用openid。请根据应用-开发配置-openid配置选择支持的字段。
        // data.setBuyerId("2088102146225135");

        // 设置买家支付宝用户唯一标识
        data.setBuyerOpenId("074a1CcTG1LelxKe4xQC0zgNdId0nxi95b5lsNpazWYoCo5");

        // 设置小程序支付中
        data.setOpAppId("2014072300007148");

        // 设置订单附加信息
        data.setBody("Iphone6 16G");

        // 设置订单包含的商品列表信息
        List<GoodsDetail> goodsDetail = new ArrayList<GoodsDetail>();
        GoodsDetail goodsDetail0 = new GoodsDetail();
        goodsDetail0.setOutSkuId("outSku_01");
        goodsDetail0.setGoodsName("ipad");
        goodsDetail0.setQuantity(10);
        goodsDetail0.setPrice("2000");
        goodsDetail0.setOutItemId("outItem_01");
        goodsDetail0.setGoodsId("apple-01");
        goodsDetail0.setGoodsCategory("34543238");
        goodsDetail0.setCategoriesTree("124868003|126232002|126252004");
        goodsDetail0.setShowUrl("http://www.alipay.com/xxx.jpg");
        goodsDetail.add(goodsDetail0);
        data.setGoodsDetail(goodsDetail);

        // 设置订单绝对超时时间
        data.setTimeExpire("2021-12-31 10:05:00");

        // 设置订单相对超时时间
        data.setTimeoutExpress("90m");

        // 设置描述结算信息
        SettleInfo settleInfo = new SettleInfo();
        settleInfo.setSettlePeriodTime("7d");
        List<SettleDetailInfo> settleDetailInfos = new ArrayList<SettleDetailInfo>();
        SettleDetailInfo settleDetailInfos0 = new SettleDetailInfo();
        settleDetailInfos0.setAmount("0.1");
        settleDetailInfos0.setTransIn("A0001");
        settleDetailInfos0.setSettleEntityType("SecondMerchant、Store");
        settleDetailInfos0.setSummaryDimension("A0001");
        settleDetailInfos0.setActualAmount("0.1");
        settleDetailInfos0.setSettleEntityId("2088xxxxx;ST_0001");
        settleDetailInfos0.setTransInType("cardAliasNo");
        settleDetailInfos.add(settleDetailInfos0);
        settleInfo.setSettleDetailInfos(settleDetailInfos);
        data.setSettleInfo(settleInfo);

        // 设置业务扩展参数
        ExtendParams extendParams = new ExtendParams();
        extendParams.setSysServiceProviderId("2088511833207846");
        extendParams.setTcInstallmentOrderId("2015042321001004720200028594");
        extendParams.setSpecifiedSellerName("XXX的跨境小铺");
        extendParams.setRoyaltyFreeze("true");
        extendParams.setCardType("S0JP0000");
        extendParams.setCreditExtInfo("{\"category\":\"CHARGE_PILE_CAR\",\"serviceId\":\"2020042800000000000001450466\"}");
        extendParams.setTradeComponentOrderId("2023060801502300000008810000005657");
        data.setExtendParams(extendParams);

        // 设置商户传入业务信息
        BusinessParams businessParams = new BusinessParams();
        businessParams.setGoodTaxes("10.00");
        businessParams.setEnterprisePayInfo("{\"category_list\":[{\"price\":\"10.24\",\"name\":\"餐饮服务\",\"category\":\"3070401000000000000\"}]}");
        businessParams.setActualOrderTime("2019-05-14 09:18:55");
        businessParams.setPriorityUnfreezeAsset("CREDIT_ASSET");
        businessParams.setCampusCard("0000306634");
        businessParams.setCardType("T0HK0000");
        businessParams.setEnterprisePayAmount("10.00");
        businessParams.setTinyAppMerchantBizType("KX_SHOPPING");
        businessParams.setMcCreateTradeIp("127.0.0.1");
        data.setBusinessParams(businessParams);

        // 设置可打折金额
        data.setDiscountableAmount("80.00");

        // 设置不可打折金额
        data.setUndiscountableAmount("8.88");

        // 设置商户门店编号
        data.setStoreId("NJ_001");

        // 设置商户操作员编号
        data.setOperatorId("Yx_001");

        // 设置商户机具终端编号
        data.setTerminalId("NJ_T_001");

        // 设置物流信息
        LogisticsDetail logisticsDetail = new LogisticsDetail();
        logisticsDetail.setLogisticsType("EXPRESS");
        data.setLogisticsDetail(logisticsDetail);

        // 设置收货人及地址信息
        ReceiverAddressInfo receiverAddressInfo = new ReceiverAddressInfo();
        receiverAddressInfo.setZip("200120");
        receiverAddressInfo.setAddress("上海市浦东新区陆家嘴银城中路501号");
        receiverAddressInfo.setName("张三");
        receiverAddressInfo.setMobile("13120180615");
        receiverAddressInfo.setDivisionCode("310115");
        data.setReceiverAddressInfo(receiverAddressInfo);

        // 设置返回参数选项
        List<String> queryOptions = new ArrayList<String>();
        queryOptions.add("enterprise_pay_info");
        queryOptions.add("hyb_amount");
        data.setQueryOptions(queryOptions);

        // 设置间联交易下
        BkAgentReqInfo bkagentReqInfo = new BkAgentReqInfo();
        bkagentReqInfo.setMerchCode("123412341234");
        bkagentReqInfo.setAcqCode("12345678901234");
        bkagentReqInfo.setDeviceType("02");
        bkagentReqInfo.setLocation("+37.28/-121.268");
        bkagentReqInfo.setSerialNum("123123123123");
        data.setBkagentReqInfo(bkagentReqInfo);

        // 设置签约参数
        SignParams agreementSignParams = new SignParams();
        SignMerchantParams subMerchant = new SignMerchantParams();
        subMerchant.setSubMerchantName("滴滴出行");
        subMerchant.setSubMerchantServiceName("滴滴出行免密支付");
        subMerchant.setSubMerchantServiceDescription("免密付车费，单次最高500");
        subMerchant.setSubMerchantId("2088123412341234");
        agreementSignParams.setSubMerchant(subMerchant);
        AccessParams accessParams = new AccessParams();
        accessParams.setChannel("ALIPAYAPP");
        agreementSignParams.setAccessParams(accessParams);
        PeriodRuleParams periodRuleParams = new PeriodRuleParams();
        periodRuleParams.setPeriod(3);
        periodRuleParams.setTotalAmount("600");
        periodRuleParams.setExecuteTime("2019-01-23");
        periodRuleParams.setSingleAmount("10.99");
        periodRuleParams.setTotalPayments(12);
        periodRuleParams.setPeriodType("DAY");
        agreementSignParams.setPeriodRuleParams(periodRuleParams);
        agreementSignParams.setSignNotifyUrl("http://www.merchant.com/receiveSignNotify");
        List<OpenApiSpecifiedChannelParamsPojo> recommendSortChannelParams = new ArrayList<OpenApiSpecifiedChannelParamsPojo>();
        OpenApiSpecifiedChannelParamsPojo recommendSortChannelParams0 = new OpenApiSpecifiedChannelParamsPojo();
        recommendSortChannelParams0.setAssetTypeCode("ALICREDIT");
        recommendSortChannelParams0.setInstId("INST_ALIPAY");
        recommendSortChannelParams.add(recommendSortChannelParams0);
        agreementSignParams.setRecommendSortChannelParams(recommendSortChannelParams);
        agreementSignParams.setExternalLogonId("13888888888");
        agreementSignParams.setPersonalProductCode("CYCLE_PAY_AUTH_P");
        agreementSignParams.setExternalAgreementNo("test20190701");
        agreementSignParams.setProductCode("GENERAL_WITHHOLDING");
        agreementSignParams.setAllowHuazhiDegrade(false);
        agreementSignParams.setSignScene("INDUSTRY|DIGITAL_MEDIA");
        agreementSignParams.setEffectTime("600");
        data.setAgreementSignParams(agreementSignParams);

        // 设置买家支付宝用户唯一标识（商户实际经营主体的小程序应用关联的买家open_id）
        data.setOpBuyerOpenId("074a1CcTG1LelxKe4xQC0zgNdId0nxi95b5lsNpazWYoCo5");

        // 第三方代调用模式下请设置app_auth_token
        CustomizedParams params = new CustomizedParams();
        params.setAppAuthToken("<-- 请填写应用授权令牌 -->");

        try {
            AlipayTradeCreateResponseModel response = api.create(data, params);
        } catch (ApiException e) {
            AlipayTradeCreateDefaultResponse errorObject = (AlipayTradeCreateDefaultResponse) e.getErrorObject();
            System.out.println("调用失败:" + errorObject);
        }
    }

    private static AlipayConfig getAlipayConfig() {
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com");
        alipayConfig.setAppId("<-- 请填写您的AppId，例如：2019091767145019 -->");
        alipayConfig.setPrivateKey("<-- 请填写您的应用私钥，例如：MIIEvQIBADANB ... ... -->");
        alipayConfig.setAlipayPublicKey("<-- 请填写您的支付宝公钥，例如：MIIBIjANBg... -->");
        return alipayConfig;
    }

}
